package com.itheima.d5_tcp2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;

public class ServerThread implements Runnable{
    private Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        try {
            InputStream is = socket.getInputStream();
            // 4、把原始的字节输入流包装成高效的输入流
            InputStreamReader isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            // 5、使用数据输入流读取客户端发送过来的消息
            InetAddress ia = socket.getInetAddress();
            while (true) {
                String content = br.readLine();
                if(content == null){
                    break;
                }
                System.out.println(ia+ "给服务端发送了："+content);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
